﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace SOSO5.Core.Helper
{
    /// <summary>
    /// 表示网页图片生成的助理类
    /// </summary>
    public static class WebPageToBitmapHelper
    {
        /// <summary>
        /// 输出指定网页的图片
        /// </summary>
        /// <param name="pageUrl">图片地址</param>
        /// <param name="width">可见宽度</param>
        /// <param name="height">可见高度</param>
        /// <param name="timeOutMilliseSeconds">超时毫秒数,默认3万毫秒（30秒）后终止浏览器对象工作线程</param>
        /// <returns>位图对象</returns>
        public static Bitmap DrawPageBitmap(string pageUrl, int width, int height, int timeOutMilliseSeconds = 1000 * 30)
        {
            Bitmap img = null;

            BrowserWorker w = new BrowserWorker(width, height, pageUrl);
            img = w.GetPageBitmap(timeOutMilliseSeconds);
            return img;
        }
    }

    /// <summary>
    /// 表示利用浏览器组件生成页面图片的类型
    /// </summary>
    internal class BrowserWorker
    {
        #region 私有字段
        private int width;
        private int height;
        private Bitmap img = null;
        private string pageUrl;
        #endregion

        /// <summary>
        /// 返回内置浏览器工作实例
        /// </summary>
        /// <param name="width">浏览器宽度</param>
        /// <param name="height">浏览器高度</param>
        /// <param name="pageUrl">页面链接</param>
        public BrowserWorker(int width, int height, string pageUrl)
        {
            this.width = width;
            this.height = height;
            this.pageUrl = pageUrl + (pageUrl.Contains("?") ? "&":"?") + Guid.NewGuid().ToString(); //更新URL使其成为唯一的，避免缓存
        }

        //独立线程工作
        private void Work()
        {
            WebBrowser browser = new WebBrowser();
            browser.ScrollBarsEnabled = false;
            browser.ScriptErrorsSuppressed = false;

            browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
            browser.Navigate(pageUrl);

            while (browser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            browser.Dispose();
        }

        //在页面加载完成时执行图片生成
        void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser browserInstance = (WebBrowser)sender;
            browserInstance.ClientSize = new Size(this.width, this.height);
            browserInstance.ScrollBarsEnabled = false;
            browserInstance.ScriptErrorsSuppressed = true;
            img = new Bitmap(browserInstance.Bounds.Width, browserInstance.Bounds.Height);
            browserInstance.BringToFront();
            browserInstance.DrawToBitmap(img, browserInstance.Bounds);
            //return;
        }

        /// <summary>
        /// 获取生成的页面图片
        /// <param name="timeOutMilliseSeconds">超时毫秒数,默认3万毫秒（30秒）后终止浏览器对象工作线程</param>
        /// </summary>        
        /// <returns></returns>
        public Bitmap GetPageBitmap(int timeOutMilliseSeconds = 1000 * 30)
        {
            ThreadStart threadStart = new ThreadStart(Work);
            Thread thread = new Thread(threadStart);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join(timeOutMilliseSeconds);
            return img;
        }
    }
}